package org.shagin.jfin.sheet;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.shagin.jfin.date.cond.DateRange;
import org.shagin.jfin.date.DateUtils;

public class SheetRowGroup {

	private DateRange interval;
	private List<DateRange> groups = new ArrayList<DateRange>();

	private static SimpleDateFormat fmt = new SimpleDateFormat("MMMM yyyy");

	public SheetRowGroup(DateRange interval) {
		this.interval = interval;
		buildGroups();
	}

	private void buildGroups() {
		Date date = interval.getStart();
		Date to = DateUtils.tomorrow(interval.getEnd());
		String groupBy = fmt.format(date);
		String priorGroupBy = groupBy;
		DateRange di = new DateRange();
		di.setStart(date);
		do {
			groupBy = fmt.format(date);
			if (!groupBy.equals(priorGroupBy)) {
				priorGroupBy = groupBy;
				di.setEnd(DateUtils.yesterday(date));
				groups.add(di);

				di = new DateRange();
				di.setStart(date);
			}
			date = DateUtils.tomorrow(date);
		} while (date.before(to));
		di.setEnd(DateUtils.yesterday(date));
		groups.add(di);
	}

	private DateRange findInterval(Date date) {
		DateRange di = null;
		for (DateRange grp : groups)
			if (grp.contain(date)) {
				di = grp;
				break;
			}
		return di;
	}

	public boolean isGroupEnd(Date date) {
		DateRange di = findInterval(date);
		if (null != di) {
			return di.isEnd(date);
		} else
			return true;
	}

	public boolean isEnd(Date date) {
		if (!groups.isEmpty()) {
			DateRange di = groups.get(groups.size() - 1);
			return di.isEnd(date);
		} else
			return true;
	}

	public String getLabel(Date date) {
		return fmt.format(date);
	}
}
